package tom.oauth2.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出成功，清除access token
 * @author ZHUFEIFEI
 */
@Slf4j
public class CustomLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {

    private final String HEAD_BEARER = "bearer";
    private final String HEAD_AUTHORIZATION = "Authorization";
    private final String PARAM_TOKEN = "access_token";

    private TokenStore tokenStore;

    protected CustomLogoutSuccessHandler(TokenStore tokenStore) {
        super();
        this.tokenStore = tokenStore;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader(HEAD_AUTHORIZATION);
        if (token == null) {
            token = request.getParameter(PARAM_TOKEN);
        }
        if (token != null) {
            if (token.startsWith(HEAD_BEARER)) {
                token = token.split(" ")[1];
            }
            OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
            if (accessToken != null) {
                log.info("remove access token : {}", token);
                this.tokenStore.removeAccessToken(accessToken);
            }
        }
    }
}
